import React, { forwardRef, PureComponent } from 'react'
import {
 Form, message, Modal, Select, Tabs, Input, Button, Tooltip,
} from 'antd'
import { connect } from '@umijs/max'
import { ProTable } from '@/components'
import styles from './index.less'

const { TabPane } = Tabs
const { Item } = Form
const { Option } = Select

class DataPreview extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      modalVisible: false,
      activeKey: '1',
      dsTableColums: [], // 数据表字段
      sheetDataColumn: [],
      sheetDataData: [],
    }
    this.dataSourceForm = React.createRef()
  }

  toggleModal = (tableNameList, selectedDataSource) => {
    const { modalVisible } = this.state
    if (!modalVisible) {
      this.setState({
        tableNameList,
        selectedDataSource,
      })
    }

    if (modalVisible) {
      this.dataSourceForm.current.resetFields()
      this.setState({
        activeKey: '1',
        dsTableColums: [], // 数据表字段
        sheetDataColumn: [],
        sheetDataData: [],
        tableNameList: [],
      })
    }

    this.setState((prevState) => ({
      modalVisible: !prevState.modalVisible,
    }))
  }

  // 选择数据表，并根据选择的数据表获取字段
  handleSelectTableName = (val) => {
    const { selectedDataSource } = this.state
    if (val) {
      this.setState({
        loading: true,
      })
    } else {
      this.setState({
        dsTableColums: [],
        sheetDataColumn: [],
        sheetDataData: [],
      })
    }

    val && this.props.dispatch({
      type: 'myApiCreate/queryPreviewData',
      params: {
        dsId: selectedDataSource,
        tableName: val,
      },
      cb: (res) => {
        const { msg, status, data } = res
        this.setState({ loading: false })
        if (status === 200) {
          const sheetDataColumn = (data?.fieldNameList || []).map(
            (item, index) => ({
              title: item?.fieldName,
              width: '1.2rem',
              dataIndex: index,
            }),
          )
          this.setState({
            dsTableColums: data?.fieldNameList || [],
            sheetDataColumn,
            sheetDataData: data?.dataList || [],
          })
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  calcValue = (item) => {
    let str = ''
    if (item?.schema) {
      str = `${item?.schema}.${item?.tableName}`
    } else {
      str = item?.tableName
    }
    return str
  }

  calcKey = (item) => (
    `${item?.tblId}${item?.tableName}`
  )

  callback = (key) => {
    this.setState({
      activeKey: key,
    })
  }

  setCopy = (val, showMessage = true) => {
    const input = document.createElement('textarea')
    input.innerHTML = val || ''
    document.body.appendChild(input)
    input.select()
    const result = document.execCommand('copy')
    document.body.removeChild(input)
    showMessage && message.success('复制成功')
    return result
  }

  render() {
    const {
      modalVisible, tableNameList, loading, activeKey, dsTableColums, sheetDataColumn, sheetDataData,
    } = this.state

    return (
      <Modal
        className={styles.data_preview}
        title="数据预览"
        visible={modalVisible}
        maskClosable={false}
        bodyStyle={{
          height: `${document.documentElement.clientHeight * 0.65}px`,
          overflowY: 'auto',
        }}
        width={720}
        footer={null}
        onCancel={this.toggleModal}
      >
        <div className={styles.container}>
          <Form
            ref={this.dataSourceForm}
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 10 }}
            autoComplete="off"
          >
            <Item
              label="数据表"
              labelCol={{ span: 2 }}
              wrapperCol={{ span: 20 }}
            >
              <Input.Group compact style={{ width: '100%' }}>
                <Item
                  noStyle
                  name="tableName"
                >
                  <Select
                    // loading={searchLoading}
                    style={{ width: '60%' }}
                    allowClear
                    showSearch
                    placeholder="请选择数据表"
                    filterOption={(input, option) => option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    onChange={this.handleSelectTableName}
                  >
                    {
                      tableNameList?.map(item => (
                        <Option key={this.calcKey(item)} value={this.calcValue(item)} title={this.calcValue(item)}>{item?.schema}{item?.schema && '.'}{item?.tableName}</Option>
                      ))
                    }
                  </Select>
                </Item>
                <Tooltip title="复制选中的数据表名">
                  <Button
                    icon={<i className="iconfont icon-fuzhi" />}
                    onClick={
                      () => {
                        const tempNameValue = this.dataSourceForm.current.getFieldValue('tableName')
                        if (!tempNameValue) {
                          message.warn('请选择要复制的数据表')
                        } else {
                          const obj = tableNameList.find((item) => this.calcValue(item) === tempNameValue)
                          let copyStr = ''
                          if (obj) {
                            if (obj.schema) {
                              copyStr = `${obj.schema}.${obj.tableName}`
                            } else {
                              copyStr = obj.tableName
                            }
                          }
                          this.setCopy(copyStr)
                        }
                      }
                    }
                  />
                </Tooltip>
              </Input.Group>
            </Item>
          </Form>
          <Tabs onChange={this.callback} activeKey={activeKey} type="card">
            <TabPane tab="字段预览" key="1">
              <ProTable
                rowKey="fieldName"
                loading={loading}
                pagination={false}
                emptyText="暂无数据"
                dataSource={dsTableColums}
                // needScroll={false}
                columns={[
                  {
                    title: '字段名称',
                    width: '50%',
                    // dataIndex: 'bindColumnName',
                    dataIndex: 'fieldName',
                  },
                  {
                    title: '字段类型',
                    width: '50%',
                    dataIndex: 'fieldType',
                  },
                ]}
              />
            </TabPane>
            <TabPane tab="数据预览" key="2">
              <div
                style={{ height: '100%', overflowY: 'auto', overflowX: 'auto' }}
              >
                <ProTable
                  style={{
                    minWidth: '100%',
                    width: `${sheetDataColumn.length * 1.2}rem`,
                  }}
                  rowKey={() => (`${Math.random()}`)}
                  loading={loading}
                  pagination={false}
                  emptyText="暂无数据"
                  dataSource={sheetDataData}
                  columns={sheetDataColumn}
                  needScroll={false}
                />
              </div>
            </TabPane>
          </Tabs>
        </div>
      </Modal>
    )
  }
}

class WrappedComponentRef extends PureComponent {
  render() {
    const { forwardedRef, ...rest } = this.props
    return (
      <DataPreview ref={forwardedRef} {...rest} />
    )
  }
}

const IComponent = connect(({ myApiCreate }) => ({ ...myApiCreate }))(WrappedComponentRef)

export default forwardRef((props, ref) => <IComponent {...props} forwardedRef={ref} />)
